package com.db.utils;

import com.db.main.Constant;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class AppInfoUtil {

    public static final Map<String, AppInfo> appInfoCached = new HashMap<>();

    public static AppInfo getAppInfo(String packageName, String homePlt) {
        AppInfo appInfo = appInfoCached.get(packageName);
        if (appInfo == null) {
            appInfo = getAppInfoFromServer(packageName, homePlt);
            if (appInfo != null) {
                synchronized (appInfoCached) {
                    appInfoCached.put(packageName, appInfo);
                }
            }
            return appInfo;
        }
        checkAppInfo(appInfo);
        return appInfo;
    }

    /**
     * 获取AppInfo信息
     *
     * @param packageName 包名
     * @param homePlt     终端平台
     * @return AppInfo信息
     */
    private static AppInfo getAppInfoFromServer(String packageName, String homePlt) {
        String getAppInfoUrl = String.format(Constant.BASE_PKG_INFO_URL + Constant.GET_APPINFO, packageName, homePlt);
        LogUtil.logApp("AppInfo", "Get AppInfo URL:" + getAppInfoUrl);
        String ret = Downloader.doDownload(getAppInfoUrl, "GET", null, null);
        JSONObject jsonObject = new JSONObject(ret);
        Object data = jsonObject.get("data");
        LogUtil.logApp("AppInfo", "packageName:" + packageName + ", getAppInfoFromServer:" + ret);
        if (jsonObject.getInt("code") == 200 && data != JSONObject.NULL) {
            AppInfo appInfo = new AppInfo();
            JSONObject dataJson = (JSONObject) data;

//            // adj7测试，android
//            String jsonString = "{ \"signatureMeta\" : null, \"programme\" : 1, \"way\" : \"adj7\", \"info\" : \"{\\\"sdkPrefix\\\":\\\"\\\",\\\"clientSdk\\\":\\\"android5.0.1\\\",\\\"versionName\\\":\\\"10.1.0\\\",\\\"packageName\\\":\\\"ng.com.fairmoney.fairmoney\\\",\\\"appSecret\\\":\\\"\\\",\\\"appToken\\\":\\\"2vhy5puex1q8\\\",\\\"defaultTracker\\\":\\\"\\\",\\\"deviceKnown\\\":\\\"\\\",\\\"environment\\\":\\\"production\\\",\\\"eventBufferingEnabled\\\":true,\\\"secretId\\\":\\\"\\\",\\\"callbackParameters\\\":\\\"\\\"}\", \"target\" : \"ng.com.fairmoney.fairmoney\", \"algorithm\" : \"{\\\"adj_signing_id\\\":\\\"1300000\\\",\\\"aes_key\\\":\\\"f110fb41676dba311f38c652c8f951ec3db456c07b9166a509bef66cd870654b\\\",\\\"algo_type\\\":\\\"adj7\\\",\\\"algorithm\\\":\\\"adj7\\\",\\\"app_salt\\\":\\\"AC08E79680A5AEAB4BC663E4C685DAA96A9465A2\\\",\\\"headers_id\\\":\\\"7\\\",\\\"hmac_key\\\":\\\"2a4cc07960d647623cc386dcefafbf25b669914d32cc8585a1ed7f920ef591eb\\\",\\\"native_version\\\":\\\"3.61.0\\\",\\\"sha256_iv\\\":\\\"0x16ba6d02,0x11a298c2,0x82187e46,0x4c148c22,0x3a5cbc15,0x06519f14,0x97b9e370,0x08ec3bec\\\",\\\"version\\\":\\\"10.1.0\\\"}\" }";
//            JSONObject dataJson = new JSONObject(jsonString);

            appInfo.appInfo = dataJson.getString("info");
            appInfo.homePlt = homePlt;
            appInfo.target = dataJson.getString("target");
            appInfo.refreshTime = System.currentTimeMillis();

            appInfo.algorithm = dataJson.optString("algorithm", "");
            appInfo.signatureMeta = dataJson.optString("signatureMeta", "");
            appInfo.programme = dataJson.optString("programme", "");
            // adj算法类型，如：adj5
            appInfo.way = dataJson.optString("way", "");

            appInfo.campaign = dataJson.optString("campaign", "");
            appInfo.adgroup = dataJson.optString("adgroup", "");
            appInfo.creative = dataJson.optString("creative", "");
            appInfo.callback = dataJson.optString("callback", "");
            return appInfo;
        }

        return null;
    }

    private static void checkAppInfo(AppInfo appInfo) {
        if (System.currentTimeMillis() - appInfo.refreshTime > TimeUnit.MINUTES.toMillis(3)) {//3 minutes before
            new Thread() {
                @Override
                public void run() {
                    AppInfo newAppInfo = getAppInfoFromServer(appInfo.packageName, appInfo.homePlt);
                    if (newAppInfo == null) {
                        return;
                    }
                    synchronized (appInfoCached) {
                        appInfoCached.put(newAppInfo.packageName, newAppInfo);
                    }
                }
            }.start();
        }
    }

    public static class AppInfo {
        public String packageName;
        public String target;
        public String appInfo;
        public String homePlt;
        public long refreshTime;

        // 纯算数据
        public String algorithm;
        // App签名数据
        public String signatureMeta;
        // 签名处理类型，0:unidbg, 1:纯算, 2:rpc
        public String programme;
        // adj算法版本，如：adj5
        public String way;

        public String campaign;
        public String adgroup;
        public String creative;
        public String callback;
    }
}
